package com.lg.algorithm.ms;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class Al1 {
    public static void main(String[] args) {
        threadPrint();
    }

    public void readToFile(InputStream is, File file){
        FileOutputStream fileOutputStream = null;
        byte[] bytes = new byte[1024];
        int size = -1;
        try {
            fileOutputStream =  new FileOutputStream(file);
            while ((size = is.read(bytes)) != -1) {
                fileOutputStream.write(bytes,0,size);
            }

        } catch (Exception e) {
            log.error("",e);
        }finally {
            try {
                is.close();
                fileOutputStream.close();
            } catch (IOException e) {
                log.error("",e);
            }

        }
    }

    /**
     * 斜向遍历一个m*n二维数组 例如
     * 1 2 3 4
     * 5 6 7 8
     * a b c d
     * 遍历结果 1 2 5 3 6 a 4 7 b 8 c d
     */
    public static void  printArr(){

    }

    /**
     *
     3个线程一个专门打印1  一个专门打印2  一个专门打印3   依次打印 1 2 3 1 2 3 1 2 3
     */
    public static void threadPrint() {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        ReentrantLock lock = new ReentrantLock();
        T t1 = new T("1");
        T t2 = new T("2");
        T t3 = new T("3");
        t1.setNextThread(t2);
        t2.setNextThread(t3);
        t3.setNextThread(t1);
        t1.start();
        t2.start();
        t3.start();
    }
    static class T extends  Thread{
        String name;
        Thread nextThread;
        T(String name) {
            this.name = name;
        }

        public void setNextThread(Thread thread) {
            this.nextThread = thread;
        }
        @SneakyThrows
        @Override
        public void run() {
            if (name != "1") {
                LockSupport.park();
            }
            for (int i = 0; i < 3; i++) {
                System.out.println(name);
                LockSupport.unpark(nextThread);
                LockSupport.park();
            }
        }
    }
}
